package com.zhk.entry.scoket;

import com.zhk.entry.common.CommandTransf;
import com.zhk.entry.model.User;

import java.io.*;
import java.net.Socket;

/**
 * 服务器端
 */
public class ClientSocket {

    public static void main(String[] args) {
        ClientSocket clientSocket = new ClientSocket();
        clientSocket.showMenu();
    }

    public void showMenu() {
        try {
            Socket socket = new Socket("localhost", 8889);
//            CommandTransf userAll = getUserAll();
//            CommandTransf userAll = save();
            CommandTransf userAll = saveGoodsAndUser();
            sendData(userAll, socket);
            getData(socket);
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 查询全部
     *
     * @return
     */
    public CommandTransf getUserAll() {
        User user = new User();
        CommandTransf commandTransf = new CommandTransf();
        commandTransf.setData(user);
        commandTransf.setCmd("getUserAll");
        return commandTransf;
    }

    /**
     * 保存
     *
     * @return
     */
    public CommandTransf save() {
        User user = new User();
        user.setId(5);
        user.setName("Tom");
        user.setAge(24);
        user.setAddress("保利叶宇");
        CommandTransf commandTransf = new CommandTransf();
        commandTransf.setData(user);
        commandTransf.setCmd("saveUser");
        return commandTransf;
    }

    /**
     * 保存商品，用户
     *
     * @return
     */
    public CommandTransf saveGoodsAndUser() {
        CommandTransf commandTransf = new CommandTransf();
        commandTransf.setCmd("saveGoodsAndUser");
        return commandTransf;
    }

    /**
     * 获取服务器端返回的数据
     *
     * @param socket
     */
    public void getData(Socket socket) {
        InputStream is;
        ObjectInputStream osi;
        CommandTransf commandTransfer = null;
        try {
            is = socket.getInputStream();
            osi = new ObjectInputStream(is);
            commandTransfer = (CommandTransf) osi.readObject();

            System.out.println("服务器端响应的数据：");
            System.out.println(commandTransfer.getData());

        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    /**
     * 向服务器发送数据
     *
     * @param commandTransfer
     * @param socket
     */
    private void sendData(CommandTransf commandTransfer, Socket socket) {
        try {
            OutputStream os = socket.getOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(os);
            oos.writeObject(commandTransfer);
            oos.flush();
            socket.shutdownOutput();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
